<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="SKU编码" prop="sku">
        <el-input
          v-model="queryParams.sku"
          placeholder="请输入SKU编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="SKU货号" prop="skuCode">
        <el-input
          v-model="queryParams.skuCode"
          placeholder="请输入SKU货号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品状态" prop="productStatus">
        <el-select v-model="queryParams.productStatus" placeholder="请选择产品状态" clearable>
          <el-option
            v-for="dict in dict.type.product_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:product:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="multiple"
          @click="handleUpdate"
          v-hasPermi="['business:product:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:product:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:product:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table ref="productTable" v-loading="loading" :data="productList" @selection-change="handleSelectionChange" row-key="productId">
      <el-table-column type="selection" width="55" align="center" reserve-selection />
      <el-table-column label="SKU编码" align="center" prop="sku" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="SKU货号" align="center" prop="skuCode" width="120" :show-overflow-tooltip="true" />
      <el-table-column label="产品名称" align="center" prop="productName" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="SKU属性" align="center" prop="skuAttr" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="核价" align="center" prop="priceCheck" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.priceCheck ? '¥' + scope.row.priceCheck : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="产品状态" align="center" prop="productStatus" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.product_status" :value="scope.row.productStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="所属店铺" align="center" prop="shopName" width="200" :show-overflow-tooltip="true" />
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:product:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:product:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改产品信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="SKU编码" prop="sku">
              <el-input v-model="form.sku" placeholder="请输入SKU编码" maxlength="100" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="SKU货号" prop="skuCode">
              <el-input v-model="form.skuCode" placeholder="请输入SKU货号（同款不同SKU可重复）" maxlength="100" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="form.productName" placeholder="请输入产品名称" maxlength="200" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="SKU属性" prop="skuAttr">
              <el-input v-model="form.skuAttr" placeholder="请输入SKU属性（如颜色、尺寸等）" maxlength="500" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="核价" prop="priceCheck">
              <el-input-number v-model="form.priceCheck" :precision="2" :min="0" :max="999999" placeholder="请输入核价" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品状态" prop="productStatus">
              <el-select v-model="form.productStatus" placeholder="请选择产品状态" style="width: 100%">
                <el-option
                  v-for="dict in dict.type.product_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="所属店铺" prop="shopId">
              <el-select v-model="form.shopId" placeholder="请选择所属店铺" style="width: 100%">
                <el-option
                  v-for="item in shopOptions"
                  :key="item.shopId"
                  :label="item.shopName"
                  :value="item.shopId"
                  :disabled="item.status == '1'"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 批量修改状态对话框 -->
    <el-dialog title="批量修改产品状态" :visible.sync="statusOpen" width="400px" append-to-body>
      <el-form ref="statusForm" :model="statusForm" :rules="statusRules" label-width="100px">
        <el-form-item label="产品状态" prop="productStatus">
          <el-select v-model="statusForm.productStatus" placeholder="请选择产品状态" style="width: 100%">
            <el-option
              v-for="dict in dict.type.product_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="">
          <div style="color: #999; font-size: 12px;">
            已选择 {{ ids.length }} 个产品，确认将这些产品的状态修改为选定状态吗？
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitStatusForm">确 定</el-button>
        <el-button @click="cancelStatus">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProduct, getProduct, delProduct, addProduct, updateProduct, checkSkuUnique, changeProductStatus } from "@/api/business/product"
import { getShopList } from "@/api/system/user"

export default {
  name: "Product",
  dicts: ['product_status'],
  data() {
    // SKU唯一性校验
    const validateSku = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('SKU编码不能为空'))
      } else {
        checkSkuUnique(value, this.form.productId).then(response => {
          if (response.data === true) {
            callback()
          } else {
            callback(new Error('SKU编码已存在'))
          }
        })
      }
    }
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品信息表格数据
      productList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 店铺选项
      shopOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sku: null,
        skuCode: null,
        productName: null,
        productStatus: null
      },
      // 表单参数
      form: {},
      // 是否显示状态修改弹出层
      statusOpen: false,
      // 状态修改表单
      statusForm: {},
      // 表单校验
      rules: {
        sku: [
          { required: true, validator: validateSku, trigger: "blur" },
          { max: 100, message: "SKU编码长度不能超过100个字符", trigger: "blur" }
        ],
        skuCode: [
          { required: true, message: "SKU货号不能为空", trigger: "blur" },
          { max: 100, message: "SKU货号长度不能超过100个字符", trigger: "blur" }
        ],
        productName: [
          { required: true, message: "产品名称不能为空", trigger: "blur" },
          { max: 200, message: "产品名称长度不能超过200个字符", trigger: "blur" }
        ],
        skuAttr: [
          { required: true, message: "SKU属性不能为空", trigger: "blur" },
          { max: 500, message: "SKU属性长度不能超过500个字符", trigger: "blur" }
        ],
        priceCheck: [
          { required: true, message: "核价不能为空", trigger: "blur" },
          { type: 'number', message: "核价必须为数字", trigger: "blur" }
        ],
        productStatus: [
          { required: true, message: "产品状态不能为空", trigger: "change" }
        ],
        shopId: [
          { required: true, message: "请选择所属店铺", trigger: "change" }
        ]
      },
      // 状态修改表单校验
      statusRules: {
        productStatus: [
          { required: true, message: "请选择产品状态", trigger: "change" }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getShopOptions()
  },
  methods: {
    /** 查询产品信息列表 */
    getList() {
      this.loading = true
      listProduct(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.productList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 获取店铺选项 */
    getShopOptions() {
      getShopList().then(response => {
        this.shopOptions = response.data
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        productId: null,
        sku: null,
        skuCode: null,
        productName: null,
        skuAttr: null,
        priceCheck: null,
        productStatus: '3',  // 默认上新备货
        shopId: null,
        remark: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.clearSelection()
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm("queryForm")
      this.clearSelection()
      this.handleQuery()
    },
    /** 清空选择 */
    clearSelection() {
      this.$refs.productTable && this.$refs.productTable.clearSelection()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.productId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加产品信息"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      // 如果是单击行内修改按钮，或者只选中一个产品
      if (row.productId || this.ids.length === 1) {
        // 单个产品编辑
        this.reset()
        const productId = row.productId || this.ids[0]
        getProduct(productId).then(response => {
          this.form = response.data
          this.open = true
          this.title = "修改产品信息"
        })
      } else if (this.ids.length > 1) {
        // 多个产品批量修改状态
        this.handleChangeStatus()
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.productId != null) {
            updateProduct(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addProduct(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const productIds = row.productId || this.ids
      this.$modal.confirm('是否确认删除选中的产品信息？').then(function() {
        return delProduct(productIds)
      }).then(() => {
        this.clearSelection()
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/product/export', {
        ...this.queryParams
      }, `product_${new Date().getTime()}.xlsx`)
    },
    /** 批量修改状态按钮操作 */
    handleChangeStatus() {
      this.statusForm = {
        productStatus: null
      }
      this.statusOpen = true
      this.$nextTick(() => {
        this.$refs["statusForm"].clearValidate()
      })
    },
    /** 取消状态修改 */
    cancelStatus() {
      this.statusOpen = false
      this.statusForm = {}
    },
    /** 提交状态修改 */
    submitStatusForm() {
      this.$refs["statusForm"].validate(valid => {
        if (valid) {
          const data = {
            productIds: this.ids,
            productStatus: this.statusForm.productStatus
          }
          changeProductStatus(data).then(response => {
            this.$modal.msgSuccess("批量修改状态成功")
            this.statusOpen = false
            this.clearSelection()
            this.getList()
          })
        }
      })
    },
  }
}
</script>

